import store from "@/store/index.js"
import config from "@/config/config.js"
import { batchSmartParse, GetFromAddress } from "@/uni-sub-base/service/api/member.js"
import { isInclude } from "@/uni-sub-base/utils/utils.js"
import { getPlatform } from "@/uni-sub-base/utils/platformUtil.js"
const mapUtil = {
    // app调用第三方地图
    toMapAPP(latitude, longitude, name) {
        let url = ""
        if (plus.os.name == "Android") {
            //判断是安卓端
            plus.nativeUI.actionSheet(
                {
                    //选择菜单
                    title: "选择地图应用",
                    cancel: "取消",
                    buttons: [
                        {
                            title: "百度地图",
                        },
                        {
                            title: "高德地图",
                        },
                    ],
                },
                function (e) {
                    let mapType = e.index
                    let mapApp = ""
                    switch (mapType) {
                        //下面是拼接url,不同系统以及不同地图都有不同的拼接字段
                        case 1:
                            url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`
                            mapApp = "百度地图"
                            break
                        case 2:
                            url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`
                            mapApp = "高德地图"
                            break
                        default:
                            break
                    }
                    if (url != "") {
                        url = encodeURI(url)
                        //plus.runtime.openURL(url,function(e){})调起手机APP应用
                        plus.runtime.openURL(url, function (e) {
                            let tipText = `本机未安装${mapApp}`
                            plus.nativeUI.alert(tipText)
                        })
                    }
                },
            )
        } else {
            // iOS上获取本机是否安装了百度高德地图，需要在manifest里配置
            // 在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
            //（如urlschemewhitelist:["iosamap","baidumap"]）
            plus.nativeUI.actionSheet(
                {
                    title: "选择地图应用",
                    cancel: "取消",
                    buttons: [
                        {
                            title: "百度地图",
                        },
                        {
                            title: "高德地图",
                        },
                    ],
                },
                function (e) {
                    let mapType = e.index
                    let mapApp = ""
                    switch (mapType) {
                        case 1:
                            url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`
                            mapApp = "百度地图"
                            break
                        case 2:
                            url = `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`
                            mapApp = "高德地图"
                            break
                        default:
                            break
                    }
                    if (url != "") {
                        url = encodeURI(url)
                        plus.runtime.openURL(url, function (e) {
                            let tipText = `本机未安装${mapApp}`
                            plus.nativeUI.alert(tipText)
                        })
                    }
                },
            )
        }
    },
    //智能识别
    getBatchSmartParse(param) {
        return new Promise((resolve, reject) => {
            GetFromAddress(param).then((res) => {
                resolve(res)
            })
        })
    },
    // h5 引入高德js
    MapLoader() {
        return new Promise((resolve, reject) => {
            if (window.AMap) {
                resolve(window.AMap)
            } else {
                var script = document.createElement("script")
                script.type = "text/javascript"
                script.async = true
                script.src = "https://webapi.amap.com/maps?v=1.4.15&key=" + config.aMapKey.web + "&callback=initAMap"
                script.onerror = reject
                document.head.appendChild(script)
            }
            window.initAMap = () => {
                resolve(window.AMap)
            }
        })
    },
    //app获取定位
    getLocationForApp() {
        return new Promise((resolve, reject) => {
            uni.getLocation({
                type: "gcj02",
                geocode: true,
                success: function (res) {
                    resolve(res)
                },
                fail(error) {
                    reject(false)
                    uni.showModal({
                        title: "未打开GPS定位",
                        content: "找不到您的位置，请开启定位",
                        showCancel: false,
                    })
                },
            })
        })
    },
    //微信小程序获取定位
    getLocationForMPWX() {
        return new Promise((resolve, reject) => {
            var that = this
            let key = ""
            var amapFile = require("@/uni-sub-base/plugins/amap-wx.js")
            key = config.aMapKey.wx
            var amapPlugin = new amapFile.AMapWX({
                key: key,
            })
            amapPlugin.getRegeo({
                success: (data) => {
                    if (data && data.length > 0) {
                        resolve(data[0])
                    }
                },
                fail: function (err) {
                    reject(err)
                    // uni.showModal({
                    // 	title: '提示',
                    // 	content: '获取定位失败，是否授权打开定位',
                    // 	success: (res) => {
                    // 		if (res.confirm) {

                    // 			if (getPlatform == 'ios') {
                    // 				plus.runtime.openURL("app-settings://");
                    // 			} else {
                    // 				var main = plus.android.runtimeMainActivity();
                    // 				var Intent = plus.android.importClass(
                    // 				"android.content.Intent");
                    // 				//可能应该直接进入应用列表的权限设置？=> android.settings.APPLICATION_SETTINGS
                    // 				var mIntent = new Intent(
                    // 					'android.settings.LOCATION_SOURCE_SETTINGS');
                    // 				main.startActivity(mIntent);
                    // 			}
                    // 		}
                    // 	}
                    // })
                },
            })
        })
    },

    // H5 获取定位
    getLocationForH5() {
        return new Promise((resolve, reject) => {
            mapUtil.MapLoader().then((resAmap) => {
                resAmap.plugin("AMap.Geolocation", () => {
                    var geolocation = new resAmap.Geolocation({
                        enableHighAccuracy: true, //是否使用高精度定位，默认:true
                        timeout: 10000, //超过10秒后停止定位，默认：5s
                        buttonPosition: "RB", //定位按钮的停靠位置
                        // buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
                    })
                    geolocation.getCurrentPosition(function (status, result) {
                        if (status == "complete") {
                            resolve(result)
                        } else {
                            reject(result)
                        }
                    })
                })
            })
        })
    },

    /**
     * 获取定位（已做兼容处理）
     * @param {Func} successCall
     * @param {Func} failCall
     */
    getLocation(successCall, failCall) {
        //#ifdef APP-PLUS
        mapUtil.getLocationForApp().then(
            (res) => {
                successCall(res)
            },
            (error) => {
                failCall(error)
            },
        )
        //#endif

        //#ifdef MP-WEIXIN
        mapUtil.getLocationForMPWX().then(
            (res) => {
                if (res.regeocodeData && res.regeocodeData.addressComponent) {
                    res.address = res.regeocodeData.addressComponent
                    res.address.postalCode = res.address.adcode
                    if (res.address.streetNumber) {
                        res.address.streetNum = res.address.streetNumber.number
                        res.address.street = res.address.streetNumber.street
                    }
                } else {
                    res.address = {}
                }
                successCall(res)
            },
            (error) => {
                failCall(error)
                // uni.showModal({
                // 	title: '提示',
                // 	content: '使用小程序需要获取定位信息',
                // 	success: (res) => {
                // 		if (res.confirm) {
                // 			uni.openSetting({
                // 				success:(res)=>{
                // 					res.authSetting = {
                // 						'scope.userLocation':true
                // 					}
                // 				}
                // 			})

                // 		}
                // 	}
                // })
            },
        )
        //#endif

        //#ifndef APP-PLUS ||MP-WEIXIN
        mapUtil.getLocationForH5().then(
            (res) => {
                res.latitude = res.position.lat
                res.longitude = res.position.lng
                res.address = res.addressComponent || {}
                res.address.postalCode = res.address.adcode
                res.address.streetNum = res.address.streetNumber
                successCall(res)
            },
            (error) => {
                // if (getPlatform == 'ios') {
                // 	plus.runtime.openURL("app-settings://");
                // } else {
                // 	var main = plus.android.runtimeMainActivity();
                // 	var Intent = plus.android.importClass(
                // 	"android.content.Intent");
                // 	//可能应该直接进入应用列表的权限设置？=> android.settings.APPLICATION_SETTINGS
                // 	var mIntent = new Intent(
                // 		'android.settings.LOCATION_SOURCE_SETTINGS');
                // 	main.startActivity(mIntent);
                // }
                failCall(error)
            },
        )
        //#endif
    },

    // 这里传入的三个参数分别是  要去的  经度 纬度 以及 地址信息
    viewMapLocation(latitude, longitude, name, address) {
        //  这里因为我是子组件传参过来了导致 经纬度变成了String 类型所以进行了一次转换
        if (latitude == 0 && longitude == 0) {
            uni.showToast({
                title: "当前经纬度为空，无法导航",
                icon: "none",
                duration: 2000,
            })
            return
        }
        let lat = parseFloat(latitude)
        let lng = parseFloat(longitude)
        // #ifdef H5
        window.location.href = `https://uri.amap.com/marker?position=${lng},${lat}&name=${name}&src=mypage&coordinate=gaode&callnative=1`
        // #endif
        // #ifndef H5

        // 获取定位信息
        uni.getLocation({
            type: "wgs84", //返回可以用于uni.openLocation的经纬度
            // 用户允许获取定位
            success: function (res) {
                if (res.errMsg == "getLocation:ok") {
                    uni.openLocation({
                        // 传入你要去的纬度
                        latitude: lat,
                        // 传入你要去的经度
                        longitude: lng,
                        name: name,
                        // 传入你要去的地址信息 不填则为空
                        address: address,
                        // 缩放大小
                        scale: 18,
                        success: function () {
                            console.log("success")
                        },
                    })
                }
            },
            // 用户拒绝获取定位后 再次点击触发
            fail: function (res) {
                if (res.errMsg == "getLocation:fail auth deny") {
                    uni.showModal({
                        content: "检测到您没打开获取信息功能权限，是否去设置打开？",
                        confirmText: "确认",
                        cancelText: "取消",
                        success: (res) => {
                            if (res.confirm) {
                                uni.openSetting({
                                    success: (res) => {},
                                })
                            } else {
                                return false
                            }
                        },
                    })
                }
            },
        })
        // #endif
    },
}
module.exports = {
    toMapAPP: mapUtil.toMapAPP,
    viewMapLocation: mapUtil.viewMapLocation,
    getLocation: mapUtil.getLocation,
    // getLocationForApp: mapUtil.getLocationForApp,
    // getLocationForMPWX: mapUtil.getLocationForMPWX,
    // getLocationForH5: mapUtil.getLocationForH5,
    getBatchSmartParse: mapUtil.getBatchSmartParse,
}
